package com.hello.auth.exception;

import com.hello.common.core.domain.R;
import com.hello.common.core.exception.ServiceException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author hello
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理JWT令牌过期异常
     */
    @ExceptionHandler(ExpiredJwtException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public R<?> handleExpiredJwtException(ExpiredJwtException e) {
        log.warn("令牌已过期: {}", e.getMessage());
        return R.fail(401, "令牌已过期，请重新登录");
    }
    
    /**
     * 处理JWT签名异常
     */
    @ExceptionHandler({UnsupportedJwtException.class, MalformedJwtException.class, SignatureException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public R<?> handleJwtException(Exception e) {
        log.warn("无效的令牌: {}", e.getMessage());
        return R.fail(401, "无效的令牌");
    }
    
    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public R<?> handleServiceException(ServiceException e) {
        log.error(e.getMessage(), e);
        return R.fail(e.getMessage());
    }
    
    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R<?> handleRuntimeException(RuntimeException e) {
        log.error("运行时异常:", e);
        return R.fail("系统错误，请联系管理员");
    }
    
    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.fail("系统错误，请联系管理员");
    }
} 